package com.example.controller;

import com.example.entity.Book;
import com.example.entity.Comment;
import com.example.repository.BookRepository;
import com.example.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;

@Controller
@RequestMapping("/books/detail")
public class BookDetailController {

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private CommentRepository commentRepository;

    @GetMapping("/{id}")
    public String showDetail(@PathVariable Long id, Model model) {
        Book book = bookRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("图书未找到: " + id));
        
        model.addAttribute("book", book);
        model.addAttribute("comments", commentRepository.findByBookIdOrderByCreateTimeDesc(id));
        model.addAttribute("newComment", new Comment());
        return "book/detail";
    }

    @PostMapping("/{id}/comment")
    public String addComment(@PathVariable Long id, @ModelAttribute Comment comment) {
        Book book = bookRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("图书未找到: " + id));
        
        comment.setBook(book);
        comment.setCreateTime(LocalDateTime.now());
        commentRepository.save(comment);
        
        return "redirect:/books/detail/" + id;
    }
} 